import { Component, OnInit } from '@angular/core';
import {
    AbstractControl,
    FormBuilder,
    FormGroup,
    Validators,
} from '@angular/forms';

@Component({
    selector: 'app-required',
    templateUrl: './required.component.html',
    styleUrls: ['./required.component.less'],
})
export class RequiredComponent implements OnInit {
    validateForm!: FormGroup;
    inputErrTip = '此项是必填项！';
    isFieldRequired: boolean = true; // Keeps track of the required state

    constructor(private fb: FormBuilder) {}

    ngOnInit(): void {
        this.initForm();
    }

    // 初始化表单
    initForm() {
        this.validateForm = this.fb.group({
            inputForm: [null, [Validators.required]],
        });
    }

    // 提交表单
    submitForm(): void {
        // 在提交前进行校验是否符合表单规则
        if (this.validateForm.valid) {
            console.log('submit', this.validateForm.value);
        } else {
            alert('必填项未填写！');
        }
    }

    logRequired(): void {
        const inputFormControl = this.validateForm.get('inputForm');
        if (inputFormControl) {
            const isRequired = inputFormControl.validator
                ? inputFormControl.validator({} as AbstractControl)?.[
                      'required'
                  ]
                : false;
            console.log(`输入框是否为必填字段: ${!!isRequired}`);
        }
    }

    changeRequired(): void {
        const inputFormControl = this.validateForm.get('inputForm');
        if (inputFormControl) {
            this.isFieldRequired = !this.isFieldRequired;
            if (this.isFieldRequired) {
                inputFormControl.setValidators([Validators.required]);
            } else {
                inputFormControl.clearValidators();
            }
            inputFormControl.updateValueAndValidity();
            console.log(`输入框必填状态已更改为: ${this.isFieldRequired}`);
        }
    }

    isRequired(control: AbstractControl): boolean {
        if (control && control.validator) {
            const validator = control.validator({} as AbstractControl);
            return validator && validator.required;
        }
        return false;
    }
}
